<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="批次名称" prop="baseAltitude">
              <el-input v-model="queryParams.batchName" placeholder="请输入批次名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="种质" prop="germplasmId">
              <el-select v-model="queryParams.germplasmId" size="small" placeholder="请选择种质">
                <el-option
                  v-for="germplasm in germplasmList"
                  :key="germplasm.germplasmId"
                  :label="germplasm.germplasmName"
                  :value="germplasm.germplasmId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="批次名称" align="center" prop="batchName" />
        <el-table-column label="种质" align="center" prop="germplasmId">
          <template #default="{ scope }">
            <data-tag :options="germplasmList" :value="scope.row.germplasmId" label-name="germplasmName" value-name="germplasmId" type="" />
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="batchHead">
          <template #default="{ scope }">
            <data-tag :options="userList" :value="scope.row.batchHead" label-name="userName" value-name="userId" type="notag" />
          </template>
        </el-table-column>
        <el-table-column label="种质图片" align="center" prop="introImg" width="180">
          <template #default="{ row }">
            <div class="image" @click="previewImage(`${image.baseUrl}${row.germplasmImg}`, row)">
              <img style="width: 50px; height: 50px" :src="`${image.baseUrl}${row.germplasmImg}`" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="种植面积(亩)" align="center" prop="cropArea" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="{ row }">
            <span>{{ parseTime(row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              v-hasPermi="['agriculture:batch:edit']"
              size="small"
              class="padding-5"
              type="primary"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >
              修改
            </el-button>
            <el-button
              v-hasPermi="['agriculture:batch:remove']"
              size="small"
              class="padding-5"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              v-hasPermi="['agriculture:batchTask:list']"
              size="small"
              class="padding-5"
              plain
              type="warning"
              icon="el-icon-s-claim"
              @click="handleBatchTask(scope.row)"
            >
              批次任务
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改作物批次对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-alert
        class="margin-bottom-10"
        title="新建批次会根据选择种质的种植流程生成批次任务，新增完成可以到批次任务管理界面调整批次任务！"
        type="warning"
        effect="light"
        show-icon
        closable
      >
      </el-alert>

      <el-form ref="cropBatchfoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="批次名称" prop="batchName">
          <el-input v-model="form.batchName" placeholder="请输入批次名称" />
        </el-form-item>
        <el-form-item label="种质" prop="germplasmId">
          <el-select v-model="form.germplasmId" placeholder="请选择种质" :disabled="!!form.batchId">
            <el-option v-for="germplasm in germplasmList" :key="germplasm.germplasmId" :label="germplasm.cropName" :value="germplasm.germplasmId" />
          </el-select>
        </el-form-item>
        <el-form-item label="种植面积" prop="cropArea">
          <el-input v-model="form.cropArea" placeholder="请输入种植面积">
            <template #append>亩</template>
          </el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            clearable
            size="default"
            type="date"
            value-format="yyyy-MM-dd"
            :disabled="!!form.batchId"
            placeholder="选择开始时间"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="batchHead">
          <el-select v-model="form.batchHead" placeholder="请选择负责人" :disabled="!!form.batchId">
            <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="image.open" :title="image.title" width="240px">
      <img style="width: 200px; height: 200px" :src="image.imgUrl" />
    </el-dialog>

    <!-- 种植计划对话框 -->
    <el-dialog v-if="batchTask.open" v-model="batchTask.open" :title="batchTask.title" width="1300px">
      <div style="height: 500px; width: 100% overflow auto">
        <task :batch-id="batchTask.batchId" :table-border="true" :mode="0" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="CropBatch" lang="ts">
import { ref, computed, onMounted } from 'vue';
import { listCropBatch, getCropBatch, delCropBatch, addCropBatch, updateCropBatch } from '@/api/agriculture/cropBatch';
import { CropBatchVO, CropBatchQuery, CropBatchForm } from '@/api/agriculture/cropBatch/types';
import { listGermplasm } from '@/api/agriculture/germplasm';
import { listBaseUser } from '@/api/system/user';
import { listLand } from '@/api/agriculture/land';
// import Task from '@/views/components/Task/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 作物批次表格数据
const batchList = ref<CropBatchVO[]>([]);
const buttonLoading = ref(false);
// 遮罩层
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

const queryFormRef = ref<ElFormInstance>();
const cropBatchfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 图片预览
const image = ref({
  baseUrl: window.location.origin + import.meta.env.VITE_APP_BASE_API,
  open: false,
  imgUrl: '',
  title: ''
});

// 种植计划
const batchTask = ref({
  open: false,
  title: '',
  batchId: null
});

// 总条数
const total = ref(0);

// 地块下拉数据
const landList = ref([]);

// 种质下拉数据
const germplasmList = ref([]);

// 用户下拉数据
const userList = ref([]);

// 弹出层标题
const title = ref('');

// 是否显示弹出层
const open = ref(false);

const initFormData: CropBatchForm = {};
const data = reactive<PageData<CropBatchForm, CropBatchQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    batchName: undefined,
    germplasmId: undefined,
    baseId: undefined
  },
  rules: {
    batchName: [
      {
        required: true,
        message: '批次名称不能为空',
        trigger: 'blur'
      }
    ],
    germplasmId: [
      {
        required: true,
        message: '种质ID不能为空',
        trigger: 'blur'
      }
    ],
    cropArea: [
      {
        required: true,
        message: '种植面积不能为空',
        trigger: 'blur'
      }
    ],
    startTime: [
      {
        required: true,
        message: '开始时间不能为空',
        trigger: 'blur'
      }
    ],
    batchHead: [
      {
        required: true,
        message: '负责人不能为空',
        trigger: 'blur'
      }
    ]
  }
});

const isAdmin = true;

const { queryParams, form, rules } = toRefs(data);

// 初始化
const getList = async () => {
  loading.value = true;
  const response = await listCropBatch(queryParams.value);
  batchList.value = response.rows;
  total.value = response.total;
  loading.value = false;
};

const getLandList = async () => {
  const response = await listLand();
  landList.value = response.rows;
};

const getGermplasmList = async () => {
  const response = await listGermplasm();
  germplasmList.value = response.rows;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  cropBatchfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CropBatchVO[]) => {
  ids.value = selection.map((item) => item.batchId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加作物批次';
};

// 修改按钮操作
const handleUpdate = async (row?: CropBatchVO) => {
  reset();
  const response = await getCropBatch(row.batchId);
  form.value = response.data;
  open.value = true;
  title.value = '修改作物批次';
};

// 提交按钮
const submitForm = () => {
  cropBatchfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.batchId) {
        await updateCropBatch(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCropBatch(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

// 删除按钮操作
const handleDelete = async (row?: CropBatchVO) => {
  const _cropBatchIds = row?.batchId || ids.value;
  await proxy?.$modal.confirm('是否确认删除作物批次信息编号为"' + _cropBatchIds + '"的数据项？').finally(() => (loading.value = false));
  await delCropBatch(_cropBatchIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

// 图片预览按钮操作
const previewImage = (imgUrl, row) => {
  image.value.title = row.version;
  image.value.open = true;
  image.value.imgUrl = imgUrl;
};

// 导出按钮操作
const handleExport = () => {
  // download('agriculture/batch/export', queryParams.value, `batch_${new Date().getTime()}.xlsx`);
};

// 种植计划按钮操作
const handleBatchTask = (row) => {
  batchTask.value.open = true;
  batchTask.value.title = '种植计划';
  batchTask.value.batchId = row.batchId;
};

onMounted(() => {
  getList();
  getLandList();
  getGermplasmList();
});
</script>
